package com.jinkaimen.kqb.ui.fragment;

import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebSettings;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.BridgeWebViewClient;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.ht.baselibs.bean.BaseGetBean;
import com.ht.baselibs.core.EventCenter;
import com.ht.baselibs.core.EventCode;
import com.ht.baselibs.retrofit.NetCallBack;
import com.ht.baselibs.ui.base.BaseFragment;
import com.ht.baselibs.utils.SharedPreferencesUtils;
import com.jinkaimen.kqb.R;
import com.jinkaimen.kqb.bean.ShareUrlBean;
import com.jinkaimen.kqb.bean.hss.ShareBean;
import com.jinkaimen.kqb.constant.Constants;
import com.jinkaimen.kqb.manager.ApiManager;
import com.tencent.smtt.utils.TbsLog;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import de.greenrobot.event.EventBus;
import retrofit2.Call;
import retrofit2.Response;


/**

 */
public class GetMoneyFragment extends BaseFragment {
    private BridgeWebView webView;

    @Override
    protected boolean hasEvent() {
        return true;
    }

    @Override
    protected View initContentView() {
        return LayoutInflater.from(mContext).inflate(R.layout.frag_get_money, null);
    }

    @Override
    protected void initChildView() {

        webView = findViewById(R.id.x5webview);
        webView.setWebViewClient(new GetMOntyWebViewClient(webView));
        //     webView.setDefaultHandler(new myHadlerCallBack());
//        String token = SharedPreferencesUtils.getString(Constants.TOKEN, "");
//        webView.loadUrl("http://hss.qianbaojiajia.com/earn/earn" + Constants.TOKEN_TITLE + token);
        //必须和js函数名字一致，注册好具体执行回调函数，类似java实现类。
        webView.registerHandler("shareLogin", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                ShareBean shareBean = JSON.parseObject(data, ShareBean.class);
                Log.e("-----", data);
                if (shareBean != null)
                    shareLogin(shareBean.url, shareBean.title, shareBean.describe);
            }
        });

        WebSettings webSetting = webView.getSettings();
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
        // webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        // webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setAppCachePath(mContext.getDir("appcache", 0).getPath());
        webSetting.setDatabasePath(mContext.getDir("databases", 0).getPath());
        webSetting.setGeolocationDatabasePath(mContext.getDir("geolocation", 0)
                .getPath());
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        // webSetting.setPreFectch(true);
        long time = System.currentTimeMillis();
//        if (mIntentUrl == null) {
//            webView.loadUrl(mHomeUrl);
//        } else {
//            webView.loadUrl(mIntentUrl.toString());
//        }
        TbsLog.d("time-cost", "cost time: "
                + (System.currentTimeMillis() - time));

    }


    @Override
    protected boolean isStaticPage() {
        return true;
    }


    @Override
    protected void setChildViewListener() {

    }

    @Override
    protected void initTitleBar() {

    }


    @Override
    protected void onEvent(int eventCode, Object data) {
        switch (eventCode) {
            case EventCode.EVENT_REFRESH_SHENHE_STATE:

                break;

        }
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {


        }

    }

    @Override
    public void onStart() {
        super.onStart();
        String token = SharedPreferencesUtils.getString(Constants.TOKEN, "");
        webView.loadUrl("http://hss.qianbaojiajia.com/earn/earn" + Constants.TOKEN_TITLE + token);
    }

    /**
     * 自定义的WebViewClient
     */
    class GetMOntyWebViewClient extends BridgeWebViewClient {

        public GetMOntyWebViewClient(BridgeWebView webView) {
            super(webView);
        }

    }

    public void onKeyDown(KeyEvent event) {
        if (webView.canGoBack()) {
            webView.goBack(); //goBack()表示返回WebView的上一页面
        } else {
            EventBus.getDefault().post(new EventCenter(EventCode.GET_MONEY_GO_BACK, event));
        }
    }

    private void shareLogin(final String url, final String title, final String describe) {
        ApiManager.getApi().shareUrl("HSS001010").enqueue(new NetCallBack<ShareUrlBean>() {
            @Override
            protected void onSuccess(Call<ShareUrlBean> call, Response<ShareUrlBean> response) {
                ShareUrlBean shareUrlBean = response.body();
                UMImage image = new UMImage(mContext, url);
                UMImage thumb = new UMImage(mContext, R.mipmap.ic_launcher);
                image.setThumb(thumb);
                UMWeb web = new UMWeb(url);
                web.setTitle(title);//标题
                web.setThumb(thumb);  //缩略图
                web.setDescription(describe);//描述
                new ShareAction(mContext)
                        .withText("hello").withMedia(web)
                        .setDisplayList(SHARE_MEDIA.QQ, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE)
                        .setCallback(shareListener)
                        .open();
            }
        });
    }

    private UMShareListener shareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            Toast.makeText(mContext, "成功了", Toast.LENGTH_LONG).show();
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(mContext, "失败" + t.getMessage(), Toast.LENGTH_LONG).show();
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(mContext, "取消了", Toast.LENGTH_LONG).show();

        }
    };

}